'use strict';
const svgCaptcha = require('svg-captcha');
const md5 = require('md5');
const sd = require('silly-datetime');
const path = require('path');
const jimp = require('jimp');
const mkdirp = require('mz-modules/mkdirp');

const Service = require('egg').Service;

class ToolsService extends Service {
    // 生成验证码
    async captcha() {
        var captcha = svgCaptcha.create({
            size: 4,
            fontSize: 50,
            width: 120,
            height: 33,
            background: "#cc9966"
        });
        this.ctx.session.code = captcha.text;        // 保存验证码上面的信息

        return captcha;
    }

    // md5加密
    async md5(str) {
        return md5(str);
    }

    async getTime() {
        var d = new Date();
        return d.getTime();
    }

    // 保存图片辅助方法
    async getUploadFile(filename) {
        // 1. 获取当前日期
        var day = sd.format(new Date(), 'YYYYMMDD');
        
        // 2. 创建图片保存的路径
        var dir = path.join(this.config.uploadDir, day);

        await mkdirp(dir);
        var d = await this.getTime();  // 图片名称追加时间，精确到毫秒
        
        // 返回图片保存的路径
        var uploadDir = path.join(dir, d+path.extname(filename));
        
        return {
            uploadDir: uploadDir,
            saveDir: uploadDir.slice(3).replace(/\\/g, '/')   // slice(3)去掉路径的 app 3个字母
        }
    }

    // 生成略缩图
    async jimpImg(target) {
        jimp.read(target, (err, lenna) => {
            if (err) throw err;
            lenna.resize(200, 200)                  // resize
                .quality(60)                        // set JPEG quality
                .write(target + '_200x200' + path.extname(target));    // save

            lenna.resize(400, 400)                  // resize
            .quality(60)                        // set JPEG quality
            .write(target + '_400x400' + path.extname(target));    // save
        });
    }
}

module.exports = ToolsService;
